package com.cmw.controller.global.err;

import com.alibaba.fastjson.JSONObject;
import com.cmw.controller.global.interceptor.WebRequestInterceptor;
import com.cmw.core.base.exception.DaoException;
import com.cmw.core.base.exception.ServiceException;
import com.cmw.core.util.PageHandler;
import com.cmw.core.util.StringHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @Remark Spring Boot 统一异常处理(处理400,500等异常)
 * @Author 程明卫
 * @Date 2017-05-17 19:12
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Value("${spring.err.400}")
    private String errPage_404;

    @Value("${spring.err.500}")
    private String errPage_500;

    /**
     * 跳转到500页面
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {Exception.class})
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        return process(req, response, e.getMessage());
    }

    private ModelAndView process(HttpServletRequest req, HttpServletResponse response, String exception){
        boolean isAjax = isAjax(response);
        String url = req.getRequestURL().toString();
        String viewName = errPage_500;
        int status = response.getStatus();
        LOG.info("url="+url+", isAjax="+isAjax+", status="+status+", exception="+exception);
       // System.out.println("status="+status);
        if(status == HttpServletResponse.SC_NOT_FOUND ||
                (StringHandler.isValidStr(exception) && exception.indexOf("No handler found for") != -1)){
            exception = "请求的路径："+url+" 不存在！";
            viewName = errPage_404;
        }
        if(isAjax){
            JSONObject json = new JSONObject();
            json.put("success", false);
            json.put("exception", exception);
            json.put("url", url);
            PageHandler.outJson(response, json);
            return null;
        }else{
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", exception);
            mav.addObject("url", url);
            mav.setViewName(viewName);
            return mav;
        }
    }

    private boolean isAjax(HttpServletResponse response){
        String contentType = response.getContentType();
        if(StringHandler.isValidStr(contentType) &&
                (contentType.indexOf("application/xml") != -1 || contentType.indexOf("application/json") != -1)){
            return  true;
        }
        return false;
    }

    /**
     * ServiceException 跳转到500页面
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = {ServiceException.class})
    public ModelAndView serviceErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        System.out.println("serviceErrorHandler.......");
        return process(req, response, e.getMessage());
    }
}
